package solution;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

// 有向图
// 邻接表实现
public class AdjacencyListDigraph<V> implements Graph<V>{
    private Map<V, Set<Edge<V>>> adj;

    public AdjacencyListDigraph() {
        this.adj = new HashMap<>();
    }

    @Override
    public Set<V> vertices(){
        return adj.keySet();
    }

    @Override
    public Set<Edge<V>> edges(){
        Set<Edge<V>> edges = new HashSet<>();
        for (Set<Edge<V>> value : adj.values()) {
            for (Edge<V> edge : value) {
                edges.add(edge);
            }
        }
        return edges;
    }

    @Override
    public void addVertex(V v) {
        adj.putIfAbsent(v, new HashSet<>());
    }

    @Override
    public void addEdge(V from, V to){
        addEdge(from, to, 0.0d);
    }

    @Override
    public void addEdge(V from, V to, double weight){
        adj.putIfAbsent(from, new HashSet<>());
        adj.get(from).add(new Edge<>(from, to, weight));
    }

    @Override
    public Set<Edge<V>> neighbors(V v){
        return adj.getOrDefault(v, Set.of()).stream().collect(Collectors.toSet());
    }
}
